package com.solcoo.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ValiCodeController {

	@RequestMapping(value = "valicode.do", method = RequestMethod.GET)
	public void valicode(HttpServletResponse response, HttpSession session) {
		response.setContentType("image/jpeg");
		response.setHeader("Cache-Control", "no-cache");

		// 创建图片对象
		int width = 80, height = 25;

		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

		Graphics2D g = (Graphics2D) image.getGraphics();
		
		// String number = "012345678abcdefghijklmnopqrstuvwxyzABCDEFGHRJKLMNOPQLSTUVWXYZ";
		// char[] nums = {number.charAt(r.nextInt(61)),number.charAt(r.nextInt(61)),number.charAt(r.nextInt(61)),number.charAt(r.nextInt(61)),number.charAt(r.nextInt(61))};
		
		// 生成随机数
		Random random = new Random();

		int one = 1 + random.nextInt(9);
		int two = 1 + random.nextInt(9);
		
		// 把随机数存到 Session 里面
		session.setAttribute("valicode", one + two);

		g.setBackground(new Color(169, 255, 187));
		g.clearRect(0, 0, width, height); // 通过使用当前绘图表面的背景色进行填充来清除指定的矩形。
		g.setPaint(Color.GRAY); // 设置画笔, 设置Paint属性
		
		for (int i = 0; i <= 50; i++) {
			g.drawArc(0, random.nextInt(25), random.nextInt(80), random.nextInt(25), random.nextInt(5), random.nextInt(30));
		}
		
		g.setColor(new Color(random.nextInt(156), random.nextInt(156), random.nextInt(156)));
		g.setFont(new Font(null, Font.ITALIC, 16 + random.nextInt(5)));
		g.drawString(one + "", 5, 17 + random.nextInt(6));
		g.setColor(new Color(random.nextInt(156), random.nextInt(156), random.nextInt(156)));
		g.setFont(new Font(null, Font.ITALIC, 16 + random.nextInt(5)));
		g.drawString("+", 20, 17 + random.nextInt(6));
		g.setColor(new Color(random.nextInt(156), random.nextInt(156), random.nextInt(156)));
		g.setFont(new Font(null, Font.ITALIC, 16 + random.nextInt(5)));
		g.drawString(two + "", 35, 17 + random.nextInt(6));
		g.setColor(new Color(random.nextInt(156), random.nextInt(156), random.nextInt(156)));
		g.setFont(new Font(null, Font.ITALIC, 16 + random.nextInt(5)));
		g.drawString("=", 50, 17 + random.nextInt(6));
		g.setColor(new Color(random.nextInt(156), random.nextInt(156), random.nextInt(156)));
		g.setFont(new Font(null, Font.ITALIC, 16 + random.nextInt(5)));
		g.drawString("?", 65, 17 + random.nextInt(6));
		
		g.dispose(); // 关闭画笔

		// 把图片送到客户端
		try {
			ServletOutputStream output = response.getOutputStream();
			ImageIO.write(image, "JPEG", output);
			output.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}